//
//  UIImage+FixOrientation.swift
//  TakePhoto
//
//  Created by 李陆涛 on 2018/7/24.
//  Copyright © 2018年 llt. All rights reserved.
//

import UIKit

extension UIImage {
    
    func fixOrientation() -> UIImage {
        
        return fixOrientation(imageOrientation: imageOrientation)
    }
    
    func fixOrientation(imageOrientation: UIImageOrientation) -> UIImage {
        
        let transform: CGAffineTransform = CGAffineTransform.identity
        
        
        switch imageOrientation {
        case .up,.upMirrored:
            
            return self
        case .down,.downMirrored:
            
            transform.translatedBy(x: size.width, y: size.height)
            transform.rotated(by: CGFloat.pi)
            break
        case .left,.leftMirrored:
            
            transform.translatedBy(x: size.width, y: 0)
            transform.rotated(by: CGFloat.pi / 2)
            break
        case .right,.rightMirrored:
            
            transform.translatedBy(x: 0, y: size.height)
            transform.rotated(by: -CGFloat.pi / 2)
            break
        }
        
        switch imageOrientation {
        case .upMirrored,.downMirrored:
            
            transform.translatedBy(x: size.width, y: 0)
            transform.scaledBy(x: -1, y: 1)
            break
        case .leftMirrored,.rightMirrored:
            
            transform.translatedBy(x: size.height, y: 0)
            transform.scaledBy(x: -1, y: 1)
            break
        default:
            break
        }
        
        let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: cgImage!.bitsPerComponent, bytesPerRow: 0, space: (cgImage?.colorSpace!)!, bitmapInfo: (cgImage?.bitmapInfo.rawValue)!)
        ctx?.concatenate(transform)
        
        switch imageOrientation {
        case .left,.leftMirrored,.right,.rightMirrored:
            
            ctx?.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
            break
        default:
            ctx?.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
            
        }
        
        let cgimg: CGImage = (ctx?.makeImage())!
        let img = UIImage(cgImage: cgimg)
        
        return img
    }
}
